package fatworm.query;

import java.util.Collection;
import java.util.LinkedList;

import fatworm.query.constant.Constant;

public class DistinctScan implements Scan {

	private Scan s;
	private Collection<String> fieldlist;
	private LinkedList<LinkedList<Constant>> complist;
	
	public DistinctScan(Scan s, Collection<String> fieldlist) {
		this.s = s;
		this.fieldlist = fieldlist;
		complist = new LinkedList<LinkedList<Constant>>();
	}
	
	private boolean isEqual(LinkedList<Constant> a, LinkedList<Constant> b) {
		if (a.size() != b.size())
			return false;
		
		for (int i = 0; i < a.size(); i++)
			if (!a.get(i).equals(b.get(i)))
				return false;
		
		return true;
	}
	
	private boolean isOK(LinkedList<Constant> x) {
		for (int i = 0; i < complist.size(); i++) 
			if (isEqual(complist.get(i), x))
				return false;
	
		return true;
	}
	
	public void beforeFirst() {
		s.beforeFirst();
	}
	
	public boolean next() {
		while (s.next()) {
			LinkedList<Constant> curlist = new LinkedList<Constant>();
			
			for (String name : fieldlist)
				curlist.add(s.getVal(name));
			
			if (isOK(curlist)) {
				complist.add(curlist);
				return true;
			}
		}
		return false;
	}
	
	public void close() {
		s.close();
	}
	
	public Constant getVal(String name) {
		return s.getVal(name);
	}
	
/*	public int getInt(String name) {
		return s.getInt(name);
	}
	
	public String getString(String name) {
		return s.getString(name);
	}*/
	
	public boolean hasField(String name) {
		return s.hasField(name);
	}
}